#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动脚本
包含依赖检查和错误处理，并自动下载ADB到本地adb/目录
"""

import sys
import os
import subprocess
import importlib.util
from pathlib import Path
import platform
import zipfile
import shutil
import urllib.request

ADB_DIR = os.path.join(os.path.dirname(__file__), 'adb')
ADB_BIN = None

# 根据平台设置ADB路径
if platform.system() == 'Windows':
    ADB_BIN = os.path.join(ADB_DIR, 'adb.exe')
    ADB_URL = 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip'
elif platform.system() == 'Darwin':
    ADB_BIN = os.path.join(ADB_DIR, 'adb')
    ADB_URL = 'https://dl.google.com/android/repository/platform-tools-latest-darwin.zip'
else:
    ADB_BIN = os.path.join(ADB_DIR, 'adb')
    ADB_URL = 'https://dl.google.com/android/repository/platform-tools-latest-linux.zip'


def download_and_extract_adb():
    """自动下载并解压ADB工具到adb/目录"""
    if os.path.exists(ADB_BIN):
        return True
    print(f"\n未检测到本地ADB，正在自动下载...\n下载地址: {ADB_URL}")
    zip_path = os.path.join(ADB_DIR, 'platform-tools.zip')
    os.makedirs(ADB_DIR, exist_ok=True)
    try:
        urllib.request.urlretrieve(ADB_URL, zip_path)
        print("下载完成，正在解压...")
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(ADB_DIR)
        # 将platform-tools目录下的文件移动到adb/
        pt_dir = os.path.join(ADB_DIR, 'platform-tools')
        for fname in os.listdir(pt_dir):
            shutil.move(os.path.join(pt_dir, fname), os.path.join(ADB_DIR, fname))
        shutil.rmtree(pt_dir)
        os.remove(zip_path)
        print("ADB工具已就绪！")
        # Linux/macOS下赋予adb可执行权限
        if platform.system() != 'Windows':
            os.chmod(ADB_BIN, 0o755)
        return True
    except Exception as e:
        print(f"ADB下载或解压失败: {e}")
        return False

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 7):
        print("错误: 需要Python 3.7或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    return True

def check_dependencies():
    """检查依赖包"""
    required_packages = [
        'tkinter',
        'PIL',
        'xml.etree.ElementTree',
        'json',
        'subprocess',
        'threading',
        'time',
        're',
        'datetime'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        if package == 'tkinter':
            # tkinter是Python内置模块，但需要特殊检查
            try:
                import tkinter
            except ImportError:
                missing_packages.append('tkinter')
        elif package == 'PIL':
            try:
                import PIL
            except ImportError:
                missing_packages.append('Pillow')
        else:
            spec = importlib.util.find_spec(package)
            if spec is None:
                missing_packages.append(package)
    
    if missing_packages:
        print("缺少以下依赖包:")
        for package in missing_packages:
            print(f"  - {package}")
        print("\n请运行以下命令安装依赖:")
        print("pip install -r requirements.txt")
        return False
    
    return True

def check_adb():
    """检查ADB是否可用（优先本地adb/adb(.exe)）"""
    if not os.path.exists(ADB_BIN):
        if not download_and_extract_adb():
            print("✗ 无法自动获取ADB工具")
            return False
    try:
        result = subprocess.run([ADB_BIN, 'version'], 
                              capture_output=True, text=True, encoding='utf-8')
        if result.returncode == 0:
            print(f"✓ ADB工具可用: {ADB_BIN}")
            return True
        else:
            print("✗ ADB工具不可用")
            return False
    except Exception as e:
        print(f"✗ 检查ADB时出错: {e}")
        return False

def check_android_device():
    """检查是否有Android设备连接（优先本地adb/adb(.exe)）"""
    try:
        result = subprocess.run([ADB_BIN, 'devices'], 
                              capture_output=True, text=True, encoding='utf-8')
        lines = result.stdout.strip().split('\n')[1:]  # 跳过标题行
        
        devices = []
        for line in lines:
            if line.strip() and '\t' in line:
                device_id, status = line.split('\t')
                if status == 'device':
                    devices.append(device_id)
        
        if devices:
            print(f"✓ 找到 {len(devices)} 个设备:")
            for device in devices:
                print(f"  - {device}")
            return True
        else:
            print("⚠ 未找到连接的Android设备")
            print("请确保:")
            print("  1. 设备已通过USB连接")
            print("  2. 已启用开发者选项和USB调试")
            print("  3. 设备驱动已正确安装")
            return False
    except Exception as e:
        print(f"✗ 检查设备时出错: {e}")
        return False

def create_directories():
    """创建必要的目录"""
    directories = ['exports', 'logs', 'screenshots', 'adb']
    for directory in directories:
        Path(directory).mkdir(exist_ok=True)

def main():
    """主函数"""
    print("=" * 50)
    print("安卓UI预览工具 - 启动检查")
    print("=" * 50)
    
    # 检查Python版本
    print("\n1. 检查Python版本...")
    if not check_python_version():
        return
    
    # 检查依赖包
    print("\n2. 检查依赖包...")
    if not check_dependencies():
        return
    
    # 检查ADB
    print("\n3. 检查ADB工具...")
    adb_available = check_adb()
    
    # 检查Android设备
    print("\n4. 检查Android设备...")
    device_available = check_android_device()
    
    # 创建目录
    print("\n5. 创建必要目录...")
    create_directories()
    print("✓ 目录创建完成")
    
    print("\n" + "=" * 50)
    
    if not adb_available:
        print("警告: ADB工具不可用，部分功能可能无法使用")
        print("建议先安装ADB工具")
    
    if not device_available:
        print("警告: 未找到Android设备，无法获取界面信息")
        print("建议先连接Android设备")
    
    print("\n启动应用...")
    print("=" * 50)
    
    try:
        # 导入并启动主应用，并传递ADB路径
        import main as main_app
        main_app.ADB_BIN = ADB_BIN
        main_app.main()
    except ImportError as e:
        print(f"错误: 无法导入主程序: {e}")
        print("请确保所有文件都在正确的位置")
        return
    except Exception as e:
        print(f"错误: 启动应用失败: {e}")
        import traceback
        traceback.print_exc()
        return
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except SystemExit:
        print("\n程序正常退出")
    finally:
        # 程序正常退出时，不等待用户输入，直接关闭
        pass

if __name__ == "__main__":
    main() 